<template>
  <el-card>
    <div slot="header"><span>个人中心</span></div>
    <div>管理员ID:{{ userInfo.id }}</div>
    <el-divider></el-divider>
    <div>账号：{{ userInfo.account }}</div>
    <el-divider></el-divider>
    <div>用户组：{{ userInfo.userGroup }}</div>
    <el-divider></el-divider>
    <div>创建时间：{{ userInfo.ctime }}</div>
    <el-divider></el-divider>

    <!-- action    上传图片服务器地址 -->
    <!-- show-file-list    展示上传列表 -->
    <el-upload
      class="avatar-uploader"
      :action="`${API}/users/avatar_upload`"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="userInfo.imgUrl" :src="userInfo.imgUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </el-card>
</template>

<script>
// 解构函数
import { mapState } from "vuex";
// import { getUserInfoReq } from '@/api/user';
import { updateUserAvatarReq } from "@/api/user";

export default {
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  data() {
    return {
      imageUrl: "",
      API: "http://sell.h5.itsource.cn:8087",
    };
  },
  methods: {
    // 上传成功触发的函数
    async handleAvatarSuccess(res, file) {
      // 结构函数
      let { code, msg, imgUrl } = res;
      // 判断
      if (code === 0) {
        // 发请求修改头像
        let res2 = await updateUserAvatarReq({
          imgUrl,
        });
        // 第二次解构数据，为了解决只有刷新时才能更新图片
        let { code, msg } = res2.data;
        // 判断
        if (code === 0) {
          // 初始化调用vuex actions里面的异步方法， 再次拉取用户信息
          this.$store.dispatch("user/A_getUserInfo");
        }
      }
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    // 约束上传类型 && 约束上传大小
    beforeAvatarUpload(file) {
      const isJPG = /(png|jpeg)/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是PNG 或 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>